import React, { useState, useEffect } from 'react';
import { Table, Card, Button, Space, message, Input, Typography, Row, Col, Statistic, Tag, Spin, Tooltip } from 'antd';
import { ReloadOutlined, SearchOutlined, InfoCircleOutlined, LineChartOutlined, DownloadOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import api, { dataAPI } from '../services/api';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';

const { Title, Text } = Typography;
const { Search } = Input;

interface FundInfo {
  id: number;
  fund_code: string;
  fund_name: string;
  fund_type: string;
  fund_manager: string;
  fund_company: string;
  establishment_date: string;
  fund_size: number;
  management_fee: number;
  custodian_fee: number;
  risk_level: number;
  annual_return: number;
  created_at: string;
  updated_at: string;
}

interface FundStats {
  total_funds: number;
  fund_types: { [key: string]: number };
  latest_update: string;
}

const FundInfoDetail: React.FC = () => {
  const [data, setData] = useState<FundInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState<string>('');
  const [stats, setStats] = useState<FundStats | null>(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  
  const navigate = useNavigate();

  const columns: ColumnsType<FundInfo> = [
    {
      title: '基金代码',
      dataIndex: 'fund_code',
      key: 'fund_code',
      width: 120,
      render: (code: string) => (
        <Button 
          type="link" 
          onClick={() => navigate(`/funds/${code}`)}
          style={{ padding: 0, height: 'auto' }}
        >
          {code}
        </Button>
      ),
    },
    {
      title: '基金名称',
      dataIndex: 'fund_name',
      key: 'fund_name',
      width: 250,
      ellipsis: {
        showTitle: false,
      },
      render: (name: string) => (
        <Tooltip placement="topLeft" title={name}>
          {name}
        </Tooltip>
      ),
    },
    {
      title: '基金类型',
      dataIndex: 'fund_type',
      key: 'fund_type',
      width: 120,
      render: (type: string) => {
        if (!type) return <Tag color="default">未知</Tag>;
        const colorMap: { [key: string]: string } = {
          '股票型': 'red',
          '混合型': 'orange',
          '债券型': 'green',
          '货币型': 'blue',
          '指数型': 'purple',
          'QDII': 'cyan',
        };
        return <Tag color={colorMap[type] || 'default'}>{type}</Tag>;
      },
    },
    {
      title: '基金经理',
      dataIndex: 'fund_manager',
      key: 'fund_manager',
      width: 150,
      ellipsis: {
        showTitle: false,
      },
      render: (manager: string) => (
        <Tooltip placement="topLeft" title={manager}>
          {manager || '-'}
        </Tooltip>
      ),
    },
    {
      title: '基金公司',
      dataIndex: 'fund_company',
      key: 'fund_company',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (company: string) => (
        <Tooltip placement="topLeft" title={company}>
          {company || '-'}
        </Tooltip>
      ),
    },
    {
      title: '成立日期',
      dataIndex: 'establishment_date',
      key: 'establishment_date',
      width: 120,
      render: (date: string) => {
        if (!date) return '-';
        return dayjs(date).format('YYYY-MM-DD');
      },
    },
    {
      title: '基金规模(亿元)',
      dataIndex: 'fund_size',
      key: 'fund_size',
      width: 130,
      render: (size: number) => {
        if (size === null || size === undefined) return '-';
        return (size / 100000000).toFixed(2);
      },
    },
    {
      title: '管理费率(%)',
      dataIndex: 'management_fee',
      key: 'management_fee',
      width: 120,
      render: (fee: number) => {
        if (fee === null || fee === undefined) return '-';
        return (fee * 100).toFixed(2) + '%';
      },
    },
    {
      title: '托管费率(%)',
      dataIndex: 'custodian_fee',
      key: 'custodian_fee',
      width: 120,
      render: (fee: number) => {
        if (fee === null || fee === undefined) return '-';
        return (fee * 100).toFixed(2) + '%';
      },
    },
    {
      title: '年化收益率(%)',
      dataIndex: 'annual_return',
      key: 'annual_return',
      width: 130,
      render: (return_rate: number) => {
        if (return_rate === null || return_rate === undefined) return '-';
        return (return_rate * 100).toFixed(2) + '%';
      },
    },
    {
      title: '风险等级',
      dataIndex: 'risk_level',
      key: 'risk_level',
      width: 100,
      render: (level: number) => {
        const riskLevels: { [key: number]: string } = {
          1: '保守型',
          2: '稳健型', 
          3: '平衡型',
          4: '成长型',
          5: '激进型'
        };
        const colors: { [key: number]: string } = {
          1: 'green',
          2: 'blue',
          3: 'orange',
          4: 'red',
          5: 'purple'
        };
        return <Tag color={colors[level] || 'default'}>{riskLevels[level] || '未知'}</Tag>;
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      key: 'updated_at',
      width: 150,
      render: (date: string) => {
        if (!date) return '-';
        return dayjs(date).format('YYYY-MM-DD HH:mm');
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="link" 
            size="small" 
            icon={<LineChartOutlined />}
            onClick={() => navigate(`/funds/${record.fund_code}`)}
          >
            详情
          </Button>
          <Button 
            type="link" 
            size="small" 
            icon={<InfoCircleOutlined />}
            onClick={() => navigate(`/funds/${record.fund_code}`)}
          >
            净值
          </Button>
        </Space>
      ),
    },
  ];

  const fetchData = async (page = 1, pageSize = 20, search = '') => {
    setLoading(true);
    try {
      const params: any = {
        page,
        page_size: pageSize,
      };
      
      if (search) {
        params.search = search;
      }
      
      const response = await dataAPI.getFunds(params);
      
      setData(response.results || []);
      setPagination({
        current: page,
        pageSize,
        total: response.total_count || 0,
      });
    } catch (error: any) {
      console.error('获取基金数据失败:', error);
      message.error('获取基金数据失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchStats = async () => {
    try {
      const response = await dataAPI.getFundStatistics();
      setStats(response);
    } catch (error: any) {
      console.error('获取统计数据失败:', error);
    }
  };

  const handleSearch = (value: string) => {
    setSearchText(value);
    fetchData(1, pagination.pageSize, value);
  };

  const handleRefresh = () => {
    fetchData(pagination.current, pagination.pageSize, searchText);
    fetchStats();
  };

  const handleTableChange = (paginationConfig: any) => {
    fetchData(paginationConfig.current, paginationConfig.pageSize, searchText);
  };

  const exportData = async () => {
    try {
      const response = await dataAPI.exportFundData(searchText);
      
      const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `基金详细信息_${dayjs().format('YYYY-MM-DD')}.xlsx`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      message.success('导出成功');
    } catch (error: any) {
      console.error('导出失败:', error);
      message.error('导出失败');
    }
  };

  useEffect(() => {
    fetchData();
    fetchStats();
  }, []);

  return (
    <div style={{ padding: '24px' }}>
      <Title level={2}>基金详细信息</Title>
      
      {/* 统计信息 */}
      {stats && (
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={6}>
            <Card>
              <Statistic
                title="基金总数"
                value={stats.total_funds}
                suffix="只"
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="股票型基金"
                value={stats.fund_types['股票型'] || 0}
                suffix="只"
                valueStyle={{ color: '#f5222d' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="混合型基金"
                value={stats.fund_types['混合型'] || 0}
                suffix="只"
                valueStyle={{ color: '#fa8c16' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="债券型基金"
                value={stats.fund_types['债券型'] || 0}
                suffix="只"
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
        </Row>
      )}
      
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Row justify="space-between" align="middle">
            <Col>
              <Space>
                <Search
                  placeholder="搜索基金代码或名称"
                  allowClear
                  style={{ width: 300 }}
                  onSearch={handleSearch}
                  enterButton={<SearchOutlined />}
                />
              </Space>
            </Col>
            <Col>
              <Space>
                <Button 
                  icon={<DownloadOutlined />} 
                  onClick={exportData}
                >
                  导出数据
                </Button>
                <Button 
                  icon={<ReloadOutlined />} 
                  onClick={handleRefresh}
                  loading={loading}
                >
                  刷新
                </Button>
              </Space>
            </Col>
          </Row>
        </div>
        
        <Table
          columns={columns}
          dataSource={data}
          loading={loading}
          rowKey="id"
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
          onChange={handleTableChange}
          scroll={{ x: 1400 }}
          size="small"
        />
      </Card>
    </div>
  );
};

export default FundInfoDetail;